package com.hpjpw.idoapp.service;

import com.hpjpw.ido.domain.Student;
import com.hpjpw.ido.domain.Teacher;
import com.hpjpw.ido.domain.Worker;
import com.hpjpw.ido.service.IStudentService;
import com.hpjpw.ido.service.ITeacherService;
import com.hpjpw.ido.service.IWorkerService;
import com.hpjpw.idoapp.domain.StudentImportVo;
import com.hpjpw.idoapp.domain.TeacherImportVo;
import com.hpjpw.idoapp.domain.WorkerRegisterVo;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @BelongsProject: ruoyi
 * @BelongsPackage: com.hpjpw.idoapp.service
 * @Author: hpj
 * @CreateTime: 2021-01-04 16:36
 * @Description: 老师与学生导入
 */
@Service
public class UserImportService {
    private static final Logger log = LoggerFactory.getLogger(UserImportService.class);
    @Autowired
    ISysUserService userService;
    @Autowired
    ITeacherService teacherService;
    @Autowired
    IStudentService studentService;
    @Autowired
    private IWorkerService workerService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysConfigService configService;

    public String importTeacherUser(List<TeacherImportVo> teacherImportVoList, String operatorName) {
        if (StringUtils.isNull(teacherImportVoList) || teacherImportVoList.size() == 0) {
            throw new CustomException("导入老师数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (TeacherImportVo importVo : teacherImportVoList) {
            try {
                // 验证是否存在这个
                SysUser u = userMapper.selectUserByUserName("t" + importVo.getNumber());
                Teacher t = teacherService.selectTeacherByNumber(importVo.getNumber());
                if (StringUtils.isNull(u)) {
                    if (StringUtils.isNull(t)) {
                        createTeacherUser(importVo, password, operatorName);
                        successNum++;
                        successMsg.append("<br/>").append(successNum).append("、职工号 ").append(importVo.getNumber()).append(" 导入成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、职工号 ").append(importVo.getNumber()).append(" 已存在");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、登录账号 t").append(importVo.getNumber()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、职工号 " + importVo.getNumber() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Transactional
    public boolean createTeacherUser(TeacherImportVo importVo, String password, String operatorName) {
        if (StringUtils.isNull(importVo))
            return false;
        Long[] longs1 = new Long[1];
        longs1[0] = UserConstants.TEACHER_ROLE_ID;
        Long[] longs2 = new Long[1];
        longs2[0] = UserConstants.TEACHER_POST_ID;
        SysUser sysUser = createUser(UserConstants.TEACHER_DEPT_ID, "t" + importVo.getNumber(),
                importVo.getNickName(), importVo.getEmail(),
                importVo.getPhoneNumber(), importVo.getSex(),
                longs1, longs2, password, operatorName);
        userService.insertUser(sysUser);
        Teacher teacher = new Teacher();
        teacher.setUserId(sysUser.getUserId());
        teacher.setName(importVo.getNickName());
        teacher.setNumber(importVo.getNumber());
        teacher.setAreaId(importVo.getAreaId());
        teacherService.insertTeacher(teacher);
        return true;
    }

    public String importStudentUser(List<StudentImportVo> studentImportVo, String operatorName) {
        if (StringUtils.isNull(studentImportVo) || studentImportVo.size() == 0) {
            throw new CustomException("导入学生数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (StudentImportVo importVo : studentImportVo) {
            try {
                // 验证是否存在这个学生
                SysUser u = userMapper.selectUserByUserName("s" + importVo.getNumber());
                Student s = studentService.selectStudentByNumber(importVo.getNumber());
                if (StringUtils.isNull(u)) {
                    if (StringUtils.isNull(s)) {
                        createStudentUser(importVo, password, operatorName);
                        successNum++;
                        successMsg.append("<br/>").append(successNum).append("、学号 ").append(importVo.getNumber()).append(" 导入成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、学号 ").append(importVo.getNumber()).append(" 已存在");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、登录账号 t").append(importVo.getNumber()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学号 " + importVo.getNumber() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Transactional
    public boolean createStudentUser(StudentImportVo importVo, String password, String operatorName) {
        if (StringUtils.isNull(importVo))
            return false;
        Long[] longs1 = new Long[1];
        longs1[0] = UserConstants.STUDENT_ROLE_ID;
        Long[] longs2 = new Long[1];
        longs2[0] = UserConstants.STUDENT_POST_ID;
        SysUser sysUser = createUser(UserConstants.STUDENT_DEPT_ID, "s" + importVo.getNumber(),
                importVo.getNickName(), importVo.getEmail(),
                importVo.getPhoneNumber(), importVo.getSex(),
                longs1, longs2, password, operatorName);
        userService.insertUser(sysUser);
        Student student = new Student();
        student.setUserId(sysUser.getUserId());
        student.setName(importVo.getNickName());
        student.setNumber(importVo.getNumber());
        student.setAreaId(importVo.getAreaId());
        student.setSchool(importVo.getSchool());
        student.setMajor(importVo.getMajor());
        student.setGrade(importVo.getGrade());
        studentService.insertStudent(student);
        return true;
    }

    @Transactional
    public boolean createWorkerUser(WorkerRegisterVo workerRegisterVo, Long enterpriseId, String operatorName) {
        if (StringUtils.isNull(workerRegisterVo))
            return false;
        Long[] longs1 = new Long[1];
        longs1[0] = UserConstants.WORKER_ROLE_ID;
        Long[] longs2 = new Long[1];
        longs2[0] = UserConstants.WORKER_POST_ID;
        SysUser sysUser = createUser(UserConstants.WORKER_DEPT_ID, "w" + workerRegisterVo.getPhoneNumber(),
                workerRegisterVo.getNickName(), workerRegisterVo.getEmail(),
                workerRegisterVo.getPhoneNumber(), workerRegisterVo.getSex(),
                longs1, longs2, workerRegisterVo.getPassword(), operatorName);
        userService.insertUser(sysUser);
        Worker worker = new Worker();
        worker.setEnterpriseId(enterpriseId);
        worker.setNumber(workerRegisterVo.getNumber());
        worker.setName(workerRegisterVo.getNickName());
        worker.setUserId(sysUser.getUserId());
        workerService.insertWorker(worker);
        return true;
    }

    public SysUser createUser(Long DeptId, String UserName, String NickName, String Email, String PhoneNumber, String Sex, Long[] longs1, Long[] longs2, String password, String operatorName) {
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(DeptId);
        sysUser.setUserName(UserName);
        sysUser.setNickName(NickName);
        sysUser.setEmail(Email);
        sysUser.setPhonenumber(PhoneNumber);
        sysUser.setSex(Sex);
        sysUser.setStatus("0");
        sysUser.setRoleIds(longs1);
        sysUser.setPostIds(longs2);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setCreateBy(operatorName);
        return sysUser;
    }
}
